package com.apigen.platform.service.impl;

import com.apigen.platform.dto.TemplateRequest;
import com.apigen.platform.entity.GenTemplate;
import com.apigen.platform.mapper.GenTemplateMapper;
import com.apigen.platform.service.ITemplateService;
import com.apigen.platform.vo.TemplateVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 模板服务实现类
 *
 * @author API Generator Platform
 * @since 2025-09-24
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class TemplateServiceImpl implements ITemplateService {

    private final GenTemplateMapper templateMapper;
    private final ObjectMapper objectMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createTemplate(TemplateRequest request) {
        // 验证模板编码唯一性
        if (!isTemplateCodeUnique(request.getTemplateCode(), null)) {
            throw new RuntimeException("模板编码已存在：" + request.getTemplateCode());
        }

        GenTemplate template = new GenTemplate();
        template.setTemplateName(request.getTemplateName());
        template.setTemplateCode(request.getTemplateCode());
        template.setDescription(request.getDescription());
        template.setTemplateType(request.getTemplateType());
        template.setTechStack(request.getTechStack());
        template.setUseCase(request.getUseCase());
        template.setVersion(request.getVersion());
        template.setAuthor(request.getAuthor());
        template.setLicense(request.getLicense());
        template.setHomepage(request.getHomepage());
        template.setRepositoryUrl(request.getRepositoryUrl());
        template.setDemoUrl(request.getDemoUrl());
        template.setDocumentUrl(request.getDocumentUrl());
        template.setCoverImage(request.getCoverImage());
        template.setScreenshots(request.getScreenshots());
        template.setTags(request.getTags());
        template.setIsEnabled(request.getIsEnabled());
        template.setIsRecommended(request.getIsRecommended());
        template.setSortOrder(request.getSortOrder());
        template.setDownloadCount(request.getDownloadCount());
        template.setRating(request.getRating());
        template.setCreatorId(1000L); // TODO: 从当前用户获取

        // 转换复杂对象为JSON字符串
        try {
            if (request.getTemplateConfig() != null) {
                template.setTemplateConfig(objectMapper.writeValueAsString(request.getTemplateConfig()));
            }
            if (request.getDependencies() != null) {
                template.setDependencies(objectMapper.writeValueAsString(request.getDependencies()));
            }
            if (request.getFeatures() != null) {
                template.setFeatures(objectMapper.writeValueAsString(request.getFeatures()));
            }
        } catch (Exception e) {
            throw new RuntimeException("配置信息序列化失败：" + e.getMessage());
        }

        templateMapper.insert(template);
        
        log.info("创建模板成功：{}", request.getTemplateName());
        return template.getTemplateId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateTemplate(TemplateRequest request) {
        if (request.getTemplateId() == null) {
            throw new RuntimeException("模板ID不能为空");
        }

        // 验证模板编码唯一性
        if (!isTemplateCodeUnique(request.getTemplateCode(), request.getTemplateId())) {
            throw new RuntimeException("模板编码已存在：" + request.getTemplateCode());
        }

        GenTemplate template = new GenTemplate();
        template.setTemplateId(request.getTemplateId());
        template.setTemplateName(request.getTemplateName());
        template.setTemplateCode(request.getTemplateCode());
        template.setDescription(request.getDescription());
        template.setTemplateType(request.getTemplateType());
        template.setTechStack(request.getTechStack());
        template.setUseCase(request.getUseCase());
        template.setVersion(request.getVersion());
        template.setAuthor(request.getAuthor());
        template.setLicense(request.getLicense());
        template.setHomepage(request.getHomepage());
        template.setRepositoryUrl(request.getRepositoryUrl());
        template.setDemoUrl(request.getDemoUrl());
        template.setDocumentUrl(request.getDocumentUrl());
        template.setCoverImage(request.getCoverImage());
        template.setScreenshots(request.getScreenshots());
        template.setTags(request.getTags());
        template.setIsEnabled(request.getIsEnabled());
        template.setIsRecommended(request.getIsRecommended());
        template.setSortOrder(request.getSortOrder());
        template.setUpdateTime(LocalDateTime.now());

        // 转换复杂对象为JSON字符串
        try {
            if (request.getTemplateConfig() != null) {
                template.setTemplateConfig(objectMapper.writeValueAsString(request.getTemplateConfig()));
            }
            if (request.getDependencies() != null) {
                template.setDependencies(objectMapper.writeValueAsString(request.getDependencies()));
            }
            if (request.getFeatures() != null) {
                template.setFeatures(objectMapper.writeValueAsString(request.getFeatures()));
            }
        } catch (Exception e) {
            throw new RuntimeException("配置信息序列化失败：" + e.getMessage());
        }

        int updated = templateMapper.updateById(template);
        
        log.info("更新模板成功：{}", request.getTemplateName());
        return updated > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteTemplates(List<Long> templateIds) {
        try {
            int deleted = templateMapper.deleteBatchIds(templateIds);
            log.info("删除{}个模板成功", deleted);
            return deleted > 0;
        } catch (Exception e) {
            log.error("删除模板失败：{}", e.getMessage());
            throw new RuntimeException("删除模板失败：" + e.getMessage());
        }
    }

    @Override
    public TemplateVO getTemplateDetail(Long templateId) {
        GenTemplate template = templateMapper.selectById(templateId);
        if (template == null) {
            throw new RuntimeException("模板不存在");
        }

        return convertToVO(template, true);
    }

    @Override
    public Page<TemplateVO> getTemplateList(String templateType, String techStack, String tags, 
                                          Boolean isRecommended, Long current, Long size) {
        Page<GenTemplate> page = new Page<>(current, size);
        LambdaQueryWrapper<GenTemplate> queryWrapper = new LambdaQueryWrapper<>();

        if (StringUtils.hasText(templateType)) {
            queryWrapper.eq(GenTemplate::getTemplateType, templateType);
        }
        if (StringUtils.hasText(techStack)) {
            queryWrapper.like(GenTemplate::getTechStack, techStack);
        }
        if (StringUtils.hasText(tags)) {
            queryWrapper.like(GenTemplate::getTags, tags);
        }
        if (isRecommended != null) {
            queryWrapper.eq(GenTemplate::getIsRecommended, isRecommended);
        }

        queryWrapper.eq(GenTemplate::getIsEnabled, true)
                   .orderByDesc(GenTemplate::getIsRecommended)
                   .orderByAsc(GenTemplate::getSortOrder)
                   .orderByDesc(GenTemplate::getDownloadCount);

        Page<GenTemplate> templatePage = templateMapper.selectPage(page, queryWrapper);

        // 转换为VO
        Page<TemplateVO> resultPage = new Page<>(current, size);
        resultPage.setTotal(templatePage.getTotal());

        List<TemplateVO> records = templatePage.getRecords().stream()
                .map(template -> convertToVO(template, false))
                .collect(Collectors.toList());

        resultPage.setRecords(records);
        return resultPage;
    }

    @Override
    public List<TemplateVO> getRecommendedTemplates(Integer limit) {
        LambdaQueryWrapper<GenTemplate> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(GenTemplate::getIsRecommended, true)
                   .eq(GenTemplate::getIsEnabled, true)
                   .orderByAsc(GenTemplate::getSortOrder)
                   .orderByDesc(GenTemplate::getDownloadCount)
                   .last("LIMIT " + limit);

        List<GenTemplate> templates = templateMapper.selectList(queryWrapper);
        return templates.stream()
                .map(template -> convertToVO(template, false))
                .collect(Collectors.toList());
    }

    @Override
    public List<TemplateVO> getPopularTemplates(Integer limit) {
        LambdaQueryWrapper<GenTemplate> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(GenTemplate::getIsEnabled, true)
                   .orderByDesc(GenTemplate::getDownloadCount)
                   .orderByDesc(GenTemplate::getRating)
                   .last("LIMIT " + limit);

        List<GenTemplate> templates = templateMapper.selectList(queryWrapper);
        return templates.stream()
                .map(template -> convertToVO(template, false))
                .collect(Collectors.toList());
    }

    @Override
    public Page<TemplateVO> searchTemplates(String keyword, String templateType, Long current, Long size) {
        Page<GenTemplate> page = new Page<>(current, size);
        LambdaQueryWrapper<GenTemplate> queryWrapper = new LambdaQueryWrapper<>();

        if (StringUtils.hasText(keyword)) {
            queryWrapper.and(wrapper -> 
                wrapper.like(GenTemplate::getTemplateName, keyword)
                       .or().like(GenTemplate::getDescription, keyword)
                       .or().like(GenTemplate::getTags, keyword)
                       .or().like(GenTemplate::getTechStack, keyword)
            );
        }
        if (StringUtils.hasText(templateType)) {
            queryWrapper.eq(GenTemplate::getTemplateType, templateType);
        }

        queryWrapper.eq(GenTemplate::getIsEnabled, true)
                   .orderByDesc(GenTemplate::getIsRecommended)
                   .orderByDesc(GenTemplate::getDownloadCount);

        Page<GenTemplate> templatePage = templateMapper.selectPage(page, queryWrapper);

        // 转换为VO
        Page<TemplateVO> resultPage = new Page<>(current, size);
        resultPage.setTotal(templatePage.getTotal());

        List<TemplateVO> records = templatePage.getRecords().stream()
                .map(template -> convertToVO(template, false))
                .collect(Collectors.toList());

        resultPage.setRecords(records);
        return resultPage;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean incrementDownloadCount(Long templateId) {
        try {
            GenTemplate template = templateMapper.selectById(templateId);
            if (template != null) {
                template.setDownloadCount(template.getDownloadCount() + 1);
                template.setLastDownloadTime(LocalDateTime.now());
                template.setUpdateTime(LocalDateTime.now());
                
                int updated = templateMapper.updateById(template);
                return updated > 0;
            }
            return false;
        } catch (Exception e) {
            log.error("增加下载次数失败：{}", e.getMessage());
            return false;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean rateTemplate(Long templateId, Double rating, Long userId) {
        // TODO: 实现模板评分逻辑（需要创建评分表）
        log.info("用户{}对模板{}评分：{}", userId, templateId, rating);
        return true;
    }

    @Override
    public Map<String, Object> getTemplateTypeStatistics() {
        // TODO: 实现模板分类统计
        Map<String, Object> statistics = new HashMap<>();
        statistics.put("BACKEND", 15);
        statistics.put("FRONTEND", 8);
        statistics.put("FULLSTACK", 12);
        statistics.put("API", 6);
        statistics.put("MICROSERVICE", 4);
        return statistics;
    }

    @Override
    public Map<String, Object> getDownloadStatistics(Long templateId, Integer days) {
        // TODO: 实现下载统计逻辑
        Map<String, Object> statistics = new HashMap<>();
        statistics.put("templateId", templateId);
        statistics.put("days", days);
        statistics.put("totalDownloads", 1250);
        statistics.put("dailyDownloads", Arrays.asList(25, 32, 18, 42, 28, 35, 20));
        return statistics;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long cloneTemplate(Long templateId, String newTemplateName, String newTemplateCode) {
        GenTemplate sourceTemplate = templateMapper.selectById(templateId);
        if (sourceTemplate == null) {
            throw new RuntimeException("源模板不存在");
        }

        // 验证新模板编码唯一性
        if (!isTemplateCodeUnique(newTemplateCode, null)) {
            throw new RuntimeException("模板编码已存在：" + newTemplateCode);
        }

        GenTemplate newTemplate = new GenTemplate();
        // 复制所有属性
        newTemplate.setTemplateName(newTemplateName);
        newTemplate.setTemplateCode(newTemplateCode);
        newTemplate.setDescription(sourceTemplate.getDescription() + " (克隆)");
        newTemplate.setTemplateType(sourceTemplate.getTemplateType());
        newTemplate.setTechStack(sourceTemplate.getTechStack());
        newTemplate.setUseCase(sourceTemplate.getUseCase());
        newTemplate.setVersion("1.0.0"); // 重置版本
        newTemplate.setAuthor(sourceTemplate.getAuthor());
        newTemplate.setLicense(sourceTemplate.getLicense());
        newTemplate.setTemplateConfig(sourceTemplate.getTemplateConfig());
        newTemplate.setDependencies(sourceTemplate.getDependencies());
        newTemplate.setFeatures(sourceTemplate.getFeatures());
        newTemplate.setIsEnabled(false); // 克隆的模板默认禁用
        newTemplate.setIsRecommended(false);
        newTemplate.setSortOrder(999);
        newTemplate.setDownloadCount(0);
        newTemplate.setRating(5.0);
        newTemplate.setCreatorId(1000L); // TODO: 从当前用户获取

        templateMapper.insert(newTemplate);
        
        log.info("克隆模板成功：{} -> {}", sourceTemplate.getTemplateName(), newTemplateName);
        return newTemplate.getTemplateId();
    }

    @Override
    public String exportTemplate(Long templateId) {
        // TODO: 实现模板导出逻辑
        return "/exports/template_" + templateId + "_" + System.currentTimeMillis() + ".zip";
    }

    @Override
    public Map<String, Object> importTemplate(String filePath) {
        // TODO: 实现模板导入逻辑
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("message", "模板导入功能待实现");
        result.put("filePath", filePath);
        return result;
    }

    @Override
    public Boolean isTemplateCodeUnique(String templateCode, Long excludeTemplateId) {
        LambdaQueryWrapper<GenTemplate> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(GenTemplate::getTemplateCode, templateCode);

        if (excludeTemplateId != null) {
            queryWrapper.ne(GenTemplate::getTemplateId, excludeTemplateId);
        }

        long count = templateMapper.selectCount(queryWrapper);
        return count == 0;
    }

    /**
     * 转换为VO对象
     */
    private TemplateVO convertToVO(GenTemplate template, boolean includeDetails) {
        TemplateVO.TemplateVOBuilder builder = TemplateVO.builder()
                .templateId(template.getTemplateId())
                .templateName(template.getTemplateName())
                .templateCode(template.getTemplateCode())
                .description(template.getDescription())
                .templateType(template.getTemplateType())
                .techStack(template.getTechStack())
                .useCase(template.getUseCase())
                .version(template.getVersion())
                .author(template.getAuthor())
                .license(template.getLicense())
                .homepage(template.getHomepage())
                .repositoryUrl(template.getRepositoryUrl())
                .demoUrl(template.getDemoUrl())
                .documentUrl(template.getDocumentUrl())
                .coverImage(template.getCoverImage())
                .isEnabled(template.getIsEnabled())
                .isRecommended(template.getIsRecommended())
                .sortOrder(template.getSortOrder())
                .downloadCount(template.getDownloadCount())
                .rating(template.getRating())
                .creatorId(template.getCreatorId())
                .createTime(template.getCreateTime())
                .updateTime(template.getUpdateTime())
                .lastDownloadTime(template.getLastDownloadTime());

        // 处理截图列表
        if (StringUtils.hasText(template.getScreenshots())) {
            try {
                List<String> screenshots = objectMapper.readValue(template.getScreenshots(), 
                        new TypeReference<List<String>>() {});
                builder.screenshots(screenshots);
            } catch (Exception e) {
                builder.screenshots(Arrays.asList(template.getScreenshots().split(",")));
            }
        }

        // 处理标签列表
        if (StringUtils.hasText(template.getTags())) {
            builder.tags(Arrays.asList(template.getTags().split(",")));
        }

        // 详细信息模式下包含更多数据
        if (includeDetails) {
            try {
                if (StringUtils.hasText(template.getTemplateConfig())) {
                    Map<String, Object> templateConfig = objectMapper.readValue(template.getTemplateConfig(), 
                            new TypeReference<Map<String, Object>>() {});
                    builder.templateConfig(templateConfig);
                }
                if (StringUtils.hasText(template.getDependencies())) {
                    Map<String, Object> dependencies = objectMapper.readValue(template.getDependencies(), 
                            new TypeReference<Map<String, Object>>() {});
                    builder.dependencies(dependencies);
                }
                if (StringUtils.hasText(template.getFeatures())) {
                    Map<String, Object> features = objectMapper.readValue(template.getFeatures(), 
                            new TypeReference<Map<String, Object>>() {});
                    builder.features(features);
                }
            } catch (Exception e) {
                log.warn("解析模板配置失败：{}", e.getMessage());
            }

            // 模拟统计信息
            TemplateVO.TemplateStatistics statistics = TemplateVO.TemplateStatistics.builder()
                    .todayDownloads(25)
                    .weekDownloads(180)
                    .monthDownloads(720)
                    .projectCount(89)
                    .activeUsers(156)
                    .latestVersion(template.getVersion())
                    .updateFrequency("每月")
                    .build();
            builder.statistics(statistics);
        }

        return builder.build();
    }
}










